<template>
  <a-modal :width="1200" body-style="padding: 10px 20px" v-model:visible="showEditDialog" title="下采购订单" top="8vh" :footer="false" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <template #title>
      <span>下采购订单</span>
      <a-popover position="bottom" trigger="click">
        <template #content>
          <div style="width: 600px">
            <p style="margin-bottom: 5px">采购须知</p>
            <p style="margin-bottom: 5px">1、创建采购订单必须指定采购员和收货仓（这里的收货仓是指本部门的仓库，并非业务的仓库，因为供应商交货先入到采购部的仓库，再由采购部创建入库单之后从部门仓扣减掉）</p>
            <p style="margin-bottom: 5px">2、指定供应商，默认从最近一次的采购订单上获取到相应的供应商。</p>
            <p style="margin-bottom: 5px">3、可以自定义设置采购参数项目，默认的采购参数根据“产品属性模板”配置来决定。</p>
            <p style="margin-bottom: 5px">4、结算方式：切记不要选错结算方式</p>
            <div style="margin-left: 20px">
              <p style="margin-bottom: 5px">现款：是指采购订单下到供应商，供应商必须收到货款才会发货，这种模式采购订单确认即可进入到请款池，去请款支付，所以这种模式需要在订单确认之前确定好采购金额，交货时不允许调整采购金额。</p>
              <p style="margin-bottom: 5px">现货：是指一手交钱一手交货，交一单货即可请一单款，这种模式可以在交货单上确认最终的采购金额。</p>
              <p style="margin-bottom: 5px">月结：按自然月结款，这种模式每个月初会自动根据上月已完成的交货单，生成请款单。</p>
            </div>
          </div>
        </template>
        <span class="highlight" style="font-size: 14px; margin-left: 20px">采购下单必读须知？</span>
      </a-popover>
    </template>
    <a-steps style="margin-bottom: 10px" type="arrow" :current="currentStep" small>
      <a-step>1.选择供应商，设置采购参数</a-step>
      <a-step>2.确认报价</a-step>
      <a-step>3.确认下单</a-step>
    </a-steps>
    <div class="submit-order-con">
      <div class="flex-c choose-warehouse" v-show="currentStep == 1 || currentStep == 2">
        <p>
          <span class="warningColor">*</span>
          <span>收货仓：</span>
        </p>
        <a-select v-model="warehouse" value-key="id" style="width: 240px" allow-search>
          <a-option v-for="(item, i) in warehouseList" :key="i" :value="item" :label="item.warehouseName" />
        </a-select>
        <p class="info">请选择本部门的仓库，不能选业务的仓库，因为供应商交货先入到采购部的仓库，再由采购部创建入库单入到业务的仓库。</p>
      </div>
      <!-- 第一步 -->
      <template v-if="currentStep == 1">
        <a-table
          class="table-two-line show-border-table"
          row-key="id"
          :data="purchaseItems"
          :scroll="{
            x: '100%',
            y: 'calc(100% - 80px)',
          }"
          size="mini"
          :bordered="{ cell: true }"
          :pagination="false"
        >
          <template #columns>
            <a-table-column data-index="img" title="图片" :width="60" fixed="left">
              <template #cell="{ record }">
                <ImgPopover :src="record.productImg">
                  <template #con>
                    <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                  </template>
                </ImgPopover>
              </template>
            </a-table-column>
            <a-table-column data-index="sku" title="SKU" :width="100" fixed="left">
              <template #cell="{ record }">
                <ShowSpuDetailBySku :val="record.sku" :showLimit="false" />
              </template>
            </a-table-column>
            <a-table-column data-index="productSpecs" title="SKU规格" :width="100">
              <template #cell="{ record }">
                <TextLimit :val="getProductSpecs(record)" />
              </template>
            </a-table-column>
            <a-table-column data-index="prop" :width="380">
              <template #title>
                <span>采购参数</span>
                <a-popover content="采购参数默认获取产品属性值，参数项目根据采购场景的属性模版配置而来。">
                  <icon-question-circle />
                </a-popover>
              </template>
              <template #cell="{ record, rowIndex }">
                <div class="purchase-props-w">
                  <ul class="purchase-props">
                    <li v-for="(prop, key) in record.purchaseSpecs" :key="key" :style="`width:${prop.type == 7 || prop.type == 8 ? '100' : '50'}%`">
                      <a-select size="mini" style="width: 100%" v-if="prop.code == 'X-chain'" :trigger-props="{ autoFitPopupMinWidth: true }" v-model="prop.purchaseValue" @search="getChainList" :filter-option="false" allow-clear allow-search :placeholder="prop.name" @change="changeProp(prop, rowIndex)">
                        <a-option v-for="(propVal, j) in chainList" :key="j" :value="propVal.skuName" :label="propVal.skuName" />
                      </a-select>
                      <a-select size="mini" style="width: 100%" v-else-if="prop.type == 1" v-model="prop.purchaseValue" allow-clear allow-search :trigger-props="{ autoFitPopupMinWidth: true }" :placeholder="prop.name">
                        <a-option v-for="(propVal, j) in getPropValueList(prop.code)" :key="j" :value="propVal.propValue" :label="propVal.propValue" />
                      </a-select>
                      <a-select size="mini" style="width: 100%" v-else-if="prop.type == 2" multiple :max-tag-count="1" v-model="prop.purchaseValue" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search allow-clear :placeholder="prop.name">
                        <a-option v-for="(propVal, j) in getPropValueList(prop.code)" :key="j" :value="propVal.propValue" :label="propVal.propValue" />
                      </a-select>
                      <a-select size="mini" style="width: 100%" v-else-if="prop.type == 3" v-model="prop.purchaseValue" :trigger-props="{ autoFitPopupMinWidth: true }" allow-clear allow-search :placeholder="prop.name">
                        <a-option value="true" label="是" />
                        <a-option value="false" label="否" />
                      </a-select>
                      <a-input size="mini" v-else-if="prop.type == 4" v-model="prop.purchaseValue" allow-clear :placeholder="prop.name" />
                      <a-input-number size="mini" v-else-if="prop.type == 5 || prop.type == 6" v-model="prop.purchaseValue" allow-clear :placeholder="prop.name" :min="0" hide-button>
                        <template #suffix>
                          {{ prop.unit }}
                        </template>
                      </a-input-number>
                      <div v-else-if="prop.type == 7">
                        <a-input size="mini" v-model="prop.purchaseValue[0]" style="width: 33.33%" allow-clear :placeholder="prop.name" hide-button>
                          <template #suffix>
                            {{ prop.unit }}
                          </template>
                        </a-input>
                        <a-input size="mini" v-model="prop.purchaseValue[1]" style="width: 33.33%" allow-clear :placeholder="prop.name" hide-button>
                          <template #suffix>
                            {{ prop.unit }}
                          </template>
                        </a-input>
                        <a-input size="mini" v-model="prop.purchaseValue[2]" style="width: 33.33%" allow-clear :placeholder="prop.name" hide-button>
                          <template #suffix>
                            {{ prop.unit }}
                          </template>
                        </a-input>
                      </div>
                      <div v-else-if="prop.type == 8">
                        <a-input size="mini" v-model="prop.purchaseValue[0]" style="width: 50%" :placeholder="prop.name" allow-clear hide-button>
                          <template #suffix>
                            {{ prop.unit }}
                          </template>
                        </a-input>
                        <a-input size="mini" v-model="prop.purchaseValue[1]" style="width: 50%" :placeholder="prop.name" allow-clear hide-button>
                          <template #suffix>
                            {{ prop.unit }}
                          </template>
                        </a-input>
                      </div>
                    </li>
                  </ul>
                  <div>
                    <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'purchaseSpecs', rowIndex)" />
                    <a-popover position="bottom" trigger="click">
                      <template #content>
                        <p class="props-title">采购参数属性配置</p>
                        <a-scrollbar style="height: 300px; overflow: auto">
                          <ul class="props-list">
                            <li class="flex-c-sb" v-for="(item, i) in allProps" :key="i" @click="chooseProp(item, record)">
                              <span>{{ item.name }}</span>
                              <span v-if="record.purchaseSpecs && record.purchaseSpecs[item.code]"><icon-eye /></span>
                              <span v-else><icon-eye-invisible /></span>
                            </li>
                          </ul>
                        </a-scrollbar>
                      </template>
                      <p><icon-down-circle class="edit-icon" /></p>
                    </a-popover>
                  </div>
                </div>
              </template>
            </a-table-column>
            <a-table-column data-index="remark" title="备注" :width="140">
              <template #cell="{ record, rowIndex }">
                <div class="cell flex-c" style="width: 132px">
                  <a-input v-model="record.remark" style="width: 100px" placeholder="" />
                  <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'remark', rowIndex)" />
                </div>
              </template>
            </a-table-column>
            <a-table-column title="供应商" :width="180">
              <template #title>
                <span class="warningColor">*</span>
                <span>供应商</span>
                <a-popover content="供应商，默认获取最近一次该产品的采购订单上获取">
                  <icon-question-circle />
                </a-popover>
              </template>
              <template #cell="{ record, rowIndex }">
                <div class="cell flex-c">
                  <a-select v-model="record.supplier" placeholder="" value-key="id" style="width: 140px" allow-search>
                    <a-option v-for="(item, i) in supplierList" :key="i" :value="item" :label="item.supplierName" />
                  </a-select>
                  <icon-double-down v-if="rowIndex != purchaseItems.length - 1" class="edit-icon" @click="setGlobal(record, 'supplier', rowIndex)" />
                </div>
              </template>
            </a-table-column>

            <a-table-column title="申购单号" data-index="planNo" :width="130" />
            <a-table-column title="操作" :width="60" fixed="right">
              <template #cell="{ rowIndex }">
                <a-popconfirm v-if="purchaseItems.length > 1" content="确定是否移除?" @ok="purchaseItems.splice(rowIndex, 1)" type="error">
                  <a-button type="text">移除</a-button>
                </a-popconfirm>
              </template>
            </a-table-column>
          </template>
        </a-table>
        <div class="footer-btn">
          <a-space>
            <a-button size="small" class="gray-outline" @click="closedDialog">取消</a-button>
            <a-button size="small" type="primary" @click="startQuote()" :disabled="submitLoading">下一步</a-button>
          </a-space>
        </div>
      </template>
      <!-- 第二步 -->
      <template v-if="currentStep == 2">
        <div class="order-w">
          <div class="order-item" v-for="(item, i) in orderList" :key="i">
            <template v-if="item.billItems.length">
              <div class="order-header">
                <p class="supplier-name">供应商：{{ item.supplierName }}（{{ item.supplierCode }}）</p>
                <div class="flex-c">
                  <span>结算方式：</span>
                  <a-select v-model="item.settleType" style="width: 240px">
                    <a-option v-for="settle in Object.values(settleAccounts)" :key="settle.key" :value="settle.key">{{ settle.value }}</a-option>
                  </a-select>
                  <a-popover position="bottom" trigger="click">
                    <template #content>
                      <div style="max-width: 400px">
                        <p>现款：是指采购订单下到供应商，供应商必须收到货款才会发货，这种模式采购订单确认即可进入到请款池，去请款支付，所以这种模式需要在订单确认之前确定好采购金额，交货时不允许调整采购金额。（这种方式必须填写产品单价）</p>
                        <p>现货：是指一手交钱一手交货，交一单货即可请一单款，这种模式可以在交货单上确认最终的采购金额。</p>
                        <p>月结：按自然月结款，这种模式每个月初会自动根据上月已完成的交货单，生成请款单。</p>
                      </div>
                    </template>
                    <icon-question-circle />
                  </a-popover>
                  <span style="margin-left: 20px">采购员：</span>
                  <a-select v-model="item.user" style="width: 120px" value-key="id" placeholder="" allow-search>
                    <a-option v-for="(user, j) in useBaseData.userList" :key="j" :value="user" :label="user.userName" />
                  </a-select>
                  <span style="margin-left: 20px">期望交货日期：</span>
                  <a-date-picker v-model="item.gmtExpectDelivery" style="width: 180px" />
                  <a-popover position="bottom" trigger="click" content="期望交期：要求供应商的最迟交货日期，默认取申购单的交货期">
                    <icon-question-circle />
                  </a-popover>
                </div>
              </div>
              <a-table class="table-two-line show-border-table" :data="item.billItems" :scroll="{ x: '100%' }" size="mini" :bordered="{ cell: true }" :pagination="false">
                <template #columns>
                  <a-table-column data-index="img" title="图片" :width="60" fixed="left">
                    <template #cell="{ record }">
                      <ImgPopover :src="record.productImg">
                        <template #con>
                          <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                        </template>
                      </ImgPopover>
                    </template>
                  </a-table-column>
                  <a-table-column data-index="sku" title="SKU" :width="100" fixed="left">
                    <template #cell="{ record }">
                      <ShowSpuDetailBySku :val="record.sku" :showLimit="false" />
                    </template>
                  </a-table-column>
                  <a-table-column data-index="productSpecs" title="SKU规格" :width="100">
                    <template #cell="{ record }">
                      <TextLimit :val="getProductSpecs(record)" />
                    </template>
                  </a-table-column>
                  <a-table-column data-index="planAmt" title="申购数" :width="60" />
                  <a-table-column data-index="purchaseRealAmt" title="已采购数" :width="80">
                    <template #title>
                      <span>已采购数</span>
                      <a-popover content="已采购数：该申购产品已提交采购的数量">
                        <icon-question-circle />
                      </a-popover>
                    </template>
                  </a-table-column>
                  <a-table-column data-index="num" title="本次采购数" :width="100">
                    <template #title>
                      <span>本次采购数</span>
                      <a-popover content="采购数量：默认值=申购数-已采购数">
                        <icon-question-circle />
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      <div class="cell flex-c">
                        <a-input-number :precision="0" :min="0" v-model="record.num" style="width: 60px" placeholder="" hide-button />
                        <icon-double-down v-if="rowIndex != item.billItems.length - 1" class="edit-icon" @click="setGlobal2(record, 'num', rowIndex, i)" />
                      </div>
                    </template>
                  </a-table-column>
                  <a-table-column data-index="materialPrice" title="材质单价(元/g)" :width="110">
                    <template #title>
                      <span>材质单价(元/g)</span>
                      <a-popover>
                        <template #content>
                          <p style="width: 400px">材质单价，是指采购参数材质属性对应的材质价格，默认值取申购明细上的材质单价，如果未取到则根据采购参数上的属性取当日最新的材质报价。</p>
                        </template>
                        <icon-question-circle />
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      <div class="cell flex-c">
                        <a-input-number :precision="2" :min="0" v-model="record.materialPrice" style="width: 70px" placeholder="" hide-button />
                        <icon-double-down v-if="rowIndex != item.billItems.length - 1" class="edit-icon" @click="setGlobal2(record, 'materialPrice', rowIndex, i)" />
                      </div>
                    </template>
                  </a-table-column>
                  <a-table-column data-index="productPrice" title="产品单价" :width="100">
                    <template #title>
                      <span>产品单价</span>
                      <a-popover>
                        <template #content>
                          <p style="width: 400px">产品单价：单个产品的成本价，默认值从供应商报价获取，如果没有报价则从最近一次采购订单上获取</p>
                        </template>
                        <icon-question-circle />
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      <div class="cell flex-c">
                        <a-input-number :precision="2" :min="0" v-model="record.productPrice" style="width: 60px" placeholder="" hide-button />
                        <icon-double-down v-if="rowIndex != item.billItems.length - 1" class="edit-icon" @click="setGlobal2(record, 'productPrice', rowIndex, i)" />
                      </div>
                    </template>
                  </a-table-column>
                  <a-table-column data-index="laborPrice" title="工费单价" :width="100">
                    <template #title>
                      <span>工费单价</span>
                      <a-popover>
                        <template #content>
                          <p style="width: 400px">工费：这里的工费单价是指供应商报价的组成部分，有些供应商的报价是不含工费的或者工费是包含在产品单价的，则可以不填写。</p>
                        </template>
                        <icon-question-circle />
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      <div class="cell flex-c">
                        <a-input-number :precision="2" :min="0" v-model="record.laborPrice" style="width: 60px" placeholder="" hide-button />
                        <icon-double-down v-if="rowIndex != item.billItems.length - 1" class="edit-icon" @click="setGlobal2(record, 'laborPrice', rowIndex, i)" />
                      </div>
                    </template>
                  </a-table-column>
                  <a-table-column title="税率" :width="180">
                    <template #cell="{ record, rowIndex }">
                      <div class="cell flex-c">
                        <a-select v-model="record.priceType" size="medium" style="width: 70px">
                          <a-option :value="0">不含税</a-option>
                          <a-option :value="1">含税</a-option>
                        </a-select>
                        <a-input-number v-model="record.rate" style="width: 60px" hide-button placeholder="" />
                        <span>%</span>
                        <icon-double-down v-if="rowIndex != item.billItems.length - 1" class="edit-icon" @click="setGlobalRate(record, rowIndex, i)" />
                      </div>
                    </template>
                  </a-table-column>
                  <a-table-column title="操作" :width="60" fixed="right">
                    <template #cell="{ rowIndex }">
                      <a-popconfirm content="确定是否移除?" @ok="item.billItems.splice(rowIndex, 1)" type="error">
                        <a-button type="text">移除</a-button>
                      </a-popconfirm>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </template>
          </div>
        </div>
        <div class="footer-btn">
          <a-space>
            <a-button size="small" class="gray-outline" @click="currentStep = 1">上一步</a-button>
            <a-button size="small" type="primary" @click="toStep3()">下一步</a-button>
          </a-space>
        </div>
      </template>
      <!-- 第三步 -->
      <template v-if="currentStep == 3">
        <a-table :scroll="{ y: 'calc(100% - 40px)' }" class="table-normal-line show-border-table" row-key="supplierCode" :data="orderList" :span-method="spanMethodAll" :columns="tableColumns" :expandable="expandable" :default-expand-all-rows="true" size="mini" :bordered="{ cell: true }" :pagination="false">
          <template #columns>
            <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <template v-if="item.dataIndex == 'img'" #cell="{ record }">
                <div class="order-w flex">
                  <div class="order-detail-item" style="width: 300px">
                    <p>
                      <span class="label">供应商：</span>
                      <span>{{ record.supplierName }}（{{ record.supplierCode }}）</span>
                    </p>
                  </div>
                  <div class="order-detail-item" style="width: 300px">
                    <p>
                      <span class="label">收货仓：</span>
                      <span v-if="warehouse">{{ warehouse.warehouseName }}</span>
                    </p>
                  </div>
                  <div class="order-detail-item" style="width: 300px">
                    <p><span class="label">结算方式：</span>{{ settleAccounts[record.settleType] ? settleAccounts[record.settleType].value : record.settleType }}</p>
                  </div>
                </div>
              </template>
            </a-table-column>
          </template>
          <template #expand-row="{ record }">
            <a-table class="table-two-line" :bordered="{ cell: true }" row-class="child-row" :show-header="false" row-key="id" :columns="tableColumns" :data="record.billItems" size="mini" :pagination="false">
              <template #columns>
                <a-table-column :width="1" />
                <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                  <template #cell="option">
                    <div v-if="item.dataIndex == 'img'" class="flex-c">
                      <ImgPopover :src="option.record.productImg">
                        <template #con>
                          <a-image width="50" height="50" fit="contain" :src="option.record.productImg" />
                        </template>
                      </ImgPopover>
                    </div>
                    <TextLimit v-else-if="item.dataIndex == 'productSpecs'" :val="getProductSpecs(option.record)" />
                    <div v-else-if="item.dataIndex == 'prop'" class="flex-c">
                      <a-space :size="5" wrap>
                        <template v-for="(prop, h) in option.record.purchaseSpecs" :key="h">
                          <a-tag style="margin-bottom: 5px" size="small" color="arcoblue" v-if="getStrVal(prop.purchaseValue)">{{ getStrVal(prop.purchaseValue) }}</a-tag>
                        </template>
                      </a-space>
                    </div>
                    <TextLimit v-else-if="item.dataIndex == 'remark'" :val="option.record.remark" />
                    <template v-else-if="item.dataIndex == 'rate'">
                      <p>{{ option.record.rate }}%</p>
                      <p class="price-type highlight">{{ option.record.priceType === 1 ? '含税' : '不含税' }}</p>
                    </template>
                    <span v-else-if="item.dataIndex == 'gmtExpectDelivery'">{{ $setTime(record.gmtExpectDelivery, 'YYYY-MM-DD') }}</span>
                    <span v-else-if="item.dataIndex == 'purchaseUname'">{{ record.user ? record.user.userName : '' }}</span>
                    <p v-else>{{ option.record[item.dataIndex] }}</p>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </template>
        </a-table>
        <div class="footer-btn">
          <a-space>
            <a-button size="small" class="gray-outline" @click="currentStep = 2">上一步</a-button>
            <a-button size="small" type="primary" @click="submitData" :loading="submitLoading">确认提交</a-button>
          </a-space>
        </div>
      </template>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { placePurchaseOrder } from '@/api/purchaseApplication'
  import { parseJson, getStrVal } from '@/utils'
  import { getRelatedList, pageFitting } from '@/api/product'
  import { findSupperList } from '@/api/system'
  import { cloneDeep } from 'lodash-es'
  import useBaseDataStore from '@/store/modules/base-data'

  onMounted(() => {
    getWarehouseList()
    getSupplierList()
    useBaseData.getUserList()
    getAllProps()
    setDefaultData()
    getChainList()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },

    list: {
      type: Object,
      default: () => {},
    },
  })
  const expandable = ref<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: ['test1', '测试注册'],
    width: 1,
  })
  const settleAccounts = {
    1: { key: 1, value: '月结（按月交货完成结款）' },
    2: { key: 2, value: '现货（交货即可结款' },
    3: { key: 3, value: '现款（先付款后发货）' },
  }
  const warehouseList = ref<Array<any>>([])
  const warehouse = ref<any>()
  const purchaseItems = ref<Array<any>>([])
  const supplierList = ref<Array<any>>([])
  const currentStep = ref(1)
  const showEditDialog = ref(props.isShow)
  const useBaseData = useBaseDataStore()
  const orderList = ref<Array<any>>([])
  const submitLoading = ref(false)
  const allProps = ref<Array<any>>([])
  let allPropsMap: any = {}
  let skuPropsMap: any = {}
  const propDefaultValByType = {
    1: null,
    2: [],
    3: null,
    4: null,
    5: null,
    6: null,
    7: ['', '', ''],
    8: ['', ''],
  }
  const tableColumns: Array<any> = [
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      width: 100,
    },
    {
      title: 'SKU规格',
      dataIndex: 'productSpecs',
      width: 100,
    },
    {
      title: '采购参数',
      dataIndex: 'prop',
      width: 200,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 100,
    },

    {
      title: '采购数量',
      dataIndex: 'num',
      width: 70,
    },
    {
      title: '材质单价(元/g)',
      dataIndex: 'materialPrice',
      width: 90,
    },

    {
      title: '产品单价',
      dataIndex: 'productPrice',
      width: 70,
    },
    {
      title: '工费单价',
      dataIndex: 'laborPrice',
      width: 70,
    },
    {
      title: '税率',
      dataIndex: 'rate',
      width: 60,
    },
    {
      title: '期望交期',
      dataIndex: 'gmtExpectDelivery',
      width: 90,
    },
    {
      title: '采购员',
      dataIndex: 'purchaseUname',
      width: 70,
    },
  ]
  const chainList = ref<Array<any>>([])
  const chainCatId = import.meta.env.VITE_CHAIN_CATEGORY_ID

  // 获取配链列表
  async function getChainList(val?: string) {
    const params: any = {
      keyword: val,
      keywordType: 'skuName',
      searchType: 'fuzzy',
      needCount: false,
      categoryId: chainCatId,
      pageNum: 1,
      pageSize: 50,
    }
    const res: any = await pageFitting(params)
    chainList.value = res?.data?.records || []
  }
  // 获取采购仓库
  async function getWarehouseList() {
    await useBaseData.getWareHouseList()
    warehouseList.value = useBaseData.warehouseList
  }
  // 获取所有的属性列表
  async function getAllProps() {
    const res = await getRelatedList({
      pageNum: 1,
      pageSize: 1000,
    })
    allProps.value = res?.data?.records || []
    allPropsMap = {}
    allProps.value.forEach((el: any) => {
      allPropsMap[el.code] = el
    })
  }
  // 属性属性值选择项
  function getPropValueList(code: string) {
    return allPropsMap[code]?.propValueList || []
  }
  //供应商列表
  async function getSupplierList() {
    const res: any = await findSupperList()
    supplierList.value = res?.data || []
  }
  // 点击增加或隐藏属性
  function chooseProp(prop: any, item: any) {
    item.purchaseSpecs = item.purchaseSpecs || {}
    if (item.purchaseSpecs?.[prop.code]) {
      delete item.purchaseSpecs[prop.code]
    } else {
      addProp(prop, item)
    }
  }
  function addProp(prop: any, item: any) {
    let purchaseValue: any
    // 获取产品的属性值
    let productProp = skuPropsMap?.[item.sku]?.[prop.code] || {}
    switch (prop.type) {
      case 1:
        purchaseValue = productProp.valueStr || null
        break
      case 2:
        purchaseValue = productProp.valueStrList || []
        break
      case 3:
        purchaseValue = productProp.valueBoolean || null
        break
      case 4:
        purchaseValue = productProp.valueStr || null
        break
      case 5:
        purchaseValue = productProp.valueNumber || null
        break
      case 6:
        purchaseValue = productProp.valueBigDecimal || null
        break
      case 7:
        let strs = productProp.valueStrList || []
        purchaseValue = [strs[0] || '', strs[1] || '', strs[2] || '']
      case 8:
        let strs2 = productProp.valueStrList || []
        purchaseValue = [strs2[0] || '', strs2[1] || '']
        break
      default:
        break
    }
    item.purchaseSpecs[prop.code] = {
      ...prop,
      purchaseValue: purchaseValue,
    }
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }

  // 添加初始化数据
  function setDefaultData() {
    purchaseItems.value = []
    props.list.forEach((item: any) => {
      let _item = cloneDeep(item)
      _item.purchaseSpecs = item.purchaseSpecs ? parseJson(item.purchaseSpecs, {}) : {}
      // 处理从erp过来的默认属性
      if (item.orderFrom == 'erp') {
        Object.keys(_item.purchaseSpecs).forEach((key: string) => {
          let _prop = _item.purchaseSpecs[key]
          _prop.purchaseValue = _prop.purchaseValue ? parseJson(_prop.purchaseValue, _prop.purchaseValue) : propDefaultValByType[_prop.type]
        })
      }
      if (_item.supplierCode) {
        _item.supplier = {
          supplierCode: _item.supplierCode,
          id: _item.supplierId,
          supplierName: _item.supplierName,
        }
      }
      purchaseItems.value.push(_item)
    })
  }

  //设置全局第一步
  function setGlobal(item: any, key: string, rowIndex: number) {
    const newVal = item[key]
    purchaseItems.value.forEach((el: any, index: number) => {
      if (index > rowIndex) {
        el[key] = typeof newVal == 'object' ? cloneDeep(newVal) : newVal
      }
    })
  }
  //设置全局第二步
  function setGlobal2(item: any, key: string, rowIndex: number, parentIndex: number) {
    const newVal = item[key]
    orderList.value[parentIndex].billItems.forEach((el: any, index: number) => {
      if (index > rowIndex) {
        el[key] = typeof newVal == 'object' ? cloneDeep(newVal) : newVal
      }
    })
  }
  //全局设置税率
  function setGlobalRate(item: any, rowIndex: number, parentIndex: number) {
    setGlobal2(item, 'priceType', rowIndex, parentIndex)
    setGlobal2(item, 'rate', rowIndex, parentIndex)
  }
  // 关闭
  function closedDialog() {
    showEditDialog.value = false
    emit('closed')
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'img') {
      return { rowspan: 1, colspan: 12 }
    }
  }
  function toStep3() {
    if (!warehouse.value?.warehouseCode) {
      Message.error('请选择收货仓！')
      return
    }
    let flag = false
    orderList.value = orderList.value.filter((el: any) => el.billItems?.length)
    orderList.value.forEach((el: any) => {
      el.billItems.forEach((item: any) => {
        if (!item.num || item.num < 0) {
          flag = true
        }
      })
    })
    if (flag) {
      Message.error('本次采购数量必须大于0')
      return
    }

    expandable.value.expandedRowKeys = orderList.value.map((el: any) => el.supplierCode)
    currentStep.value = 3
  }
  // 开始报价
  async function startQuote() {
    let orderMap: any = {}
    for (let item of purchaseItems.value) {
      let supplierCode = item.supplier?.supplierCode
      if (!supplierCode) {
        Message.error('请选择供应商！')
        return
      }
      if (!orderMap[supplierCode]) {
        orderMap[supplierCode] = {
          ...item.supplier,
          settleType: 1,
          billItems: [],
        }
      }
      orderMap[supplierCode].billItems.push({
        ...item,
        num: item.purchaseStayAmt,
      })
    }
    orderList.value = Object.values(orderMap)
    // 如果只有一个明细，默认当前明细的采购员和期望交货日期
    orderList.value.forEach((el: any) => {
      if (el.billItems.length === 1 && el.billItems[0].purchaseUid) {
        el.user = {
          id: el.billItems[0].purchaseUid,
          userName: el.billItems[0].purchaseUname,
        }
        el.gmtExpectDelivery = el.billItems[0].gmtExpectDelivery
      }
    })
    currentStep.value = 2
  }
  // 保存信息
  async function submitData() {
    console.log(orderList.value)
    let purchaseParams: Array<any> = []
    orderList.value.forEach((el: any) => {
      let obj: any = {
        warehouseCode: warehouse.value?.warehouseCode,
        warehouseName: warehouse.value?.warehouseName,
        supplierName: el.supplierName,
        supplierCode: el.supplierCode,
        supplierId: el.id,
        settleType: el.settleType,
        purchaseUname: el.user?.userName,
        purchaseUid: el.user?.id,
        gmtExpectDelivery: el.gmtExpectDelivery,
        billItems: [],
      }
      el.billItems.forEach((item: any) => {
        obj.billItems.push({
          laborPrice: item.laborPrice,
          materialPrice: item.materialPrice,
          planItemId: item.id,
          priceType: item.priceType,
          productId: item.productId,
          productImg: item.productImg,
          productName: item.productName,
          productPrice: item.productPrice,
          purchaseAmt: item.num,
          purchaseSpecs: JSON.stringify(item.purchaseSpecs),
          rate: item.rate,
          remark: item.remark,
          salesmanId: item.salesmanId,
          salesmanName: item.salesmanName,
          gmtExpectDelivery: el.gmtExpectDelivery,
          purchaseUname: el.user?.userName,
          purchaseUid: el.user?.id,
          settleType: el.settleType,
          supplierName: el.supplierName,
          supplierCode: el.supplierCode,
          supplierId: el.id,
          warehouseCode: warehouse.value?.warehouseCode,
          warehouseName: warehouse.value?.warehouseName,
          sku: item.sku,
          spu: item.spu,
          urgent: item.urgent,
        })
      })
      purchaseParams.push(obj)
    })
    console.log(purchaseParams)
    submitLoading.value = true
    const res: any = await placePurchaseOrder({ purchaseParams })
    submitLoading.value = false
    if (res) {
      Message.success('保存成功')
      emit('success')
      closedDialog()
    }
  }
</script>
<style lang="less" scoped>
  .submit-order-con {
    height: calc(84vh - 120px);
    .footer-btn {
      padding: 10px;
      display: flex;
      justify-content: flex-end;
    }
    .order-w {
      height: calc(100% - 80px);
      overflow: auto;
      .order-item {
        margin-bottom: 10px;
        box-shadow: 0 0 3px 1px #eee;
      }
      .order-header {
        background-color: #f1f1f1;
        padding: 10px;
        border: 1px solid var(--color-neutral-3);
        .supplier-name {
          margin-bottom: 10px;
        }
      }
    }
  }

  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }

  :deep(td.shopInfo .arco-table-cell) {
    padding: 0 !important;
  }

  .props-list {
    width: 200px;
    li {
      padding-right: 10px;
      margin-bottom: 5px;
    }
  }
  .props-title {
    margin-bottom: 5px;
  }
  .purchase-props {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    li {
      width: 50%;
      padding-right: 5px;
      margin-top: 5px;
    }
  }
  .purchase-props-w {
    display: flex;
    justify-content: space-between;
  }
  .choose-warehouse {
    margin-bottom: 10px;
    .info {
      font-size: 12px;
      margin-left: 10px;
      color: #999;
    }
  }
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
    .arco-select-view-single {
      padding: 0 5px;
    }
    .arco-input-wrapper {
      padding: 0 5px;
    }
    .arco-select-view-value {
      font-size: 12px !important;
      min-height: 26px;
    }
    .arco-input {
      font-size: 12px !important;
    }
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
      }
    }
    background-color: #fff !important;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 5px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
</style>
